import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:xr_base/common.dart';
import 'package:xr_base/string_constants.dart';
import 'package:xr_dio/xr_dio.dart';

import '../apis/apis.dart';
import '../models/account.dart';
import '../models/token.dart';
import '../util/xr_cache_util.dart';

class UserData {
  static final UserData _singletonPattern = UserData._internal();

  ///工厂构造函数
  factory UserData() {
    return _singletonPattern;
  }

  ///构造函数私有化，防止被误创建
  UserData._internal();

  /// 登录用户详细数据
  AccountData? _userBaseInfo;

  // token
  String? _token;

  String? get token => _token;

  /// 登录状态
  bool get isLogin => _isLogin;

  bool _isLogin = false;

  int? get userId => _userBaseInfo?.userId;

  String? get userSig => _userBaseInfo?.userSig;

  String? get sex => _userBaseInfo?.sex;

  /// 初始化 是否已登录
  init() {
    _token = XrCacheUtil.token;
    _userBaseInfo = XrCacheUtil.account;
    _isLogin = ObjectUtil.isNotEmpty(_token);
    debugPrint("---😆😆初始化 是否已登录,_token: $_token😆😆---");
    debugPrint("---😆😆初始化 是否已登录,sex: $sex😆😆---");
    debugPrint("---😆😆初始化 是否已登录,userId: $userId😆😆---");
    debugPrint("---😆😆初始化 是否已登录,_userBaseInfo.toJson: ${_userBaseInfo?.toJson()}😆😆---");
  }

  login(
      {required String phone,
      String occasionType = '1',
      required String smsCode,
      CancelToken? cancelToken,
      ValueChanged<String>? onOk,
      ValueChanged<String>? onFail}) async {
    HttpResponse appResponse = (await XrHttpClient.getInstance().get(Apis.login,
        queryParameters: {'phone': phone, 'occasionType': occasionType, 'areaCode': '86'},
        cancelToken: cancelToken)) as HttpResponse;
    if (appResponse.ok) {
      if (ObjectUtil.isNotEmpty(appResponse.data)) {
        // debugPrint("====登录data:" + appResponse.data.toString());
        _userBaseInfo = AccountData.fromJson(appResponse.data);
        await XrCacheUtil.setAccount(appResponse.data);
      }
      if (ObjectUtil.isNotEmpty(appResponse.token)) {
        // debugPrint("====登录token:" + appResponse.token.toString());
        _token = appResponse.token;

        /// 标识登录成功
        _isLogin = true;
        await XrCacheUtil.setToken(appResponse.token);
      }
      if (onOk != null) {
        onOk(Strings.tl_ok);
      }
    } else {
      /// 标识登录失败
      _isLogin = false;
      if (onFail != null) {
        onFail(appResponse.error.toString());
      }
    }
  }

  /// 更新完善用户个人信息
  updateUserInfo(
      {required String nickName,
      required String sex,
      ValueChanged<String>? onOk,
      ValueChanged<String>? onFail}) async {
    HttpResponse appResponse =
        (await XrHttpClient.getInstance().post(Apis.updateUserInfo, data: {'nickName': nickName, 'sex': sex}));
    if (appResponse.ok) {
      if (ObjectUtil.isNotEmpty(appResponse.data)) {
        // debugPrint("====登录data:" + appResponse.data.toString());
        _userBaseInfo = AccountData.fromJson(appResponse.data);
        await XrCacheUtil.setAccount(appResponse.data);
      }
      if (ObjectUtil.isNotEmpty(appResponse.token)) {
        // debugPrint("====登录token:" + appResponse.token.toString());
        _token = appResponse.token;

        /// 标识登录成功
        _isLogin = true;
        await XrCacheUtil.setToken(appResponse.token);
      }
      if (onOk != null) {
        onOk(Strings.tl_ok);
      }
    } else {
      if (onFail != null) {
        onFail(appResponse.error.toString());
      }
    }
  }

  /// 获取第三方token
  getChannelToken({ValueChanged<Token>? onOk, ValueChanged<String>? onFail}) async {
    HttpResponse appResponse = (await XrHttpClient.getInstance().get(Apis.getChannelToken));
    if (appResponse.ok) {
      if (ObjectUtil.isNotEmpty(appResponse.data)) {
        debugPrint("====获取第三方token,data:" + appResponse.data.toString());
        if (onOk != null) {
          onOk(Token.fromJson(appResponse.data));
        }
      }
    } else {
      if (onFail != null) {
        onFail(appResponse.error.toString());
      }
    }
  }

  /// 上传文件到七牛
  upload(
      {required String token,
      required String fileName,
      required String filePath,
      ValueChanged<String>? onOk,
      ValueChanged<String>? onFail}) async {
    Options _options = Options(headers: {'Host': Constant.qiniu_ipload_host});
    debugPrint('---😆😆上传文件到七牛, filePath:$filePath😆😆---');

    // final String _bigFile = request.params['bigFile'];
    // final String _smallFile = request.params['smallFile'];
    // final String _bigFileName = _bigFile.substring(_bigFile.lastIndexOf('/') + 1, _bigFile.length);
    // final String _smallFileName = _smallFile.substring(_smallFile.lastIndexOf('/') + 1, _smallFile.length);
    fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length);
    debugPrint('---😆😆上传文件到七牛, fileName:$fileName😆😆---');

    final MultipartFile _ml = (await MultipartFile.fromFile(filePath, filename: fileName));

    var _formData = FormData.fromMap({'upload_token': token, 'fileName': fileName, 'fileBinaryData': _ml});

    HttpResponse appResponse =
        (await XrHttpClient.getInstance().post(Constant.qiniu_ipload_host, data: _formData, options: _options));
    if (appResponse.ok) {
      if (ObjectUtil.isNotEmpty(appResponse.data)) {
        debugPrint("====上传文件到七牛data:" + appResponse.data.toString());
        if (onOk != null) {
          onOk(Strings.tl_ok);
        }
      }
    } else {
      if (onFail != null) {
        onFail(appResponse.error.toString());
      }
    }
  }

  logout({ValueChanged<String>? onOk, ValueChanged<String>? onFail}) async {
    HttpResponse appResponse = (await XrHttpClient.getInstance().post(Apis.logout));
    if (appResponse.ok) {
      removeUserData();
      if (onOk != null) {
        onOk(Strings.tl_ok);
      }
    } else {
      removeUserData();
      if (onFail != null) {
        onFail(appResponse.error.toString());
      }
    }
  }

  /// 清空相关数据
  removeUserData() {
    XrCacheUtil.removeToken();
    XrCacheUtil.removeAccount();
    _userBaseInfo = null;
    _token = null;
    _isLogin = false;
  }
}
